package cn.wygandwdn.core.serializer.kryo;

import cn.wygandwdn.common.enumeration.SerializerType;
import cn.wygandwdn.core.serializer.WtSerializer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @description:
 * @author: WYG
 * @time: 2021/10/24 17:15
 */

public class KryoSerializer implements WtSerializer {

    private static final ThreadLocal<Kryo> kryos = new ThreadLocal<>() {
        @Override
        protected Kryo initialValue() {
            Kryo kryo = new Kryo();
            kryo.setRegistrationRequired(false);
            kryo.setReferences(true);
            return kryo;
        }
    };

    @Override
    public <T> byte[] serializeToByte(T obj) {
        Kryo kryo = kryos.get();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Output output = new Output(stream);
        kryo.writeClassAndObject(output, obj);
        output.close();
        return stream.toByteArray();
    }

    @Override
    public <T> T deserializeFromByte(byte[] data, Class<T> cls) {
        Kryo kryo = kryos.get();
        ByteArrayInputStream stream = new ByteArrayInputStream(data);
        Input input = new Input(stream);
        Object o = kryo.readClassAndObject(input);
        input.close();
        return (T) o;
    }

    @Override
    public String getType() {
        return SerializerType.Kryo.getType();
    }
}
